package main

import (
	"bufio"
	"fmt"
	"os"
)

// 模拟原 Website 结构，这里只当普通行数据用
type Website struct {
	Name   string
	Url    string
	Course []string
}

func main() {
	writeTxt()
	readTxt()
}

// 写纯文本文件 —— 每行一条记录，字段用 "|" 分隔，课程用 "," 连接
func writeTxt() {
	info := []Website{
		{"Golang", "http://c.biancheng.net/golang/", []string{"http://c.biancheng.net/cplus/", "http://c.biancheng.net/linux_tutorial/"}},
		{"Java", "http://c.biancheng.net/java/", []string{"http://c.biancheng.net/socket/", "http://c.biancheng.net/python/"}},
	}

	file, err := os.Create("info.txt")
	if err != nil {
		fmt.Println("文件创建失败:", err)
		return
	}
	defer file.Close()

	w := bufio.NewWriter(file)
	for _, v := range info {
		// 拼一行：Name|Url|Course1,Course2
		line := fmt.Sprintf("%s|%s|%s\n", v.Name, v.Url, join(v.Course, ","))
		w.WriteString(line)
	}
	if err := w.Flush(); err != nil {
		fmt.Println("写入失败:", err)
		return
	}
	fmt.Println("写入成功")
}

// 读纯文本文件 —— 逐行解析
func readTxt() {
	file, err := os.Open("info.txt")
	if err != nil {
		fmt.Println("文件打开失败:", err)
		return
	}
	defer file.Close()

	var list []Website
	sc := bufio.NewScanner(file)
	for sc.Scan() {
		fields := split(sc.Text(), "|")
		if len(fields) != 3 {
			continue // 简单容错
		}
		list = append(list, Website{
			Name:   fields[0],
			Url:    fields[1],
			Course: split(fields[2], ","),
		})
	}
	if err := sc.Err(); err != nil {
		fmt.Println("读取失败:", err)
		return
	}
	fmt.Println("读取成功:")
	for _, v := range list {
		fmt.Printf("%+v\n", v)
	}
}

// --------- 小工具函数 ----------
func join(a []string, sep string) string {
	if len(a) == 0 {
		return ""
	}
	res := a[0]
	for _, s := range a[1:] {
		res += sep + s
	}
	return res
}

func split(s, sep string) []string {
	var res []string
	start := 0
	for i := 0; i < len(s); i++ {
		if s[i:i+len(sep)] == sep {
			res = append(res, s[start:i])
			start = i + len(sep)
			i += len(sep) - 1
		}
	}
	res = append(res, s[start:])
	return res
}
